<template>
	<view id="body">
		<view class="form">	
			<uni-section class="mb-10" title="1.选择发布类型" type="line" titleColor="#909399" ></uni-section>
			<view class="type-input">
				<u--input
				    placeholder="请选择发布类型"
				    border="surround" 
				    v-model="issueType"
				    @tap="typechange"
					readonly
				></u--input>
			</view>
			<u-picker :show="show" ref="uPicker" :columns="columns" @cancel="close" @confirm="confirm" @change="changeHandler"></u-picker> 
			<!-- 标题 -->
			<uni-section class="mb-10" title="2.发布标题" type="line" titleColor="#909399"></uni-section>
			<view class="title-input">
				<u--input placeholder="请输入发布标题" v-model="title"  clearable></u--input>
			</view> 
			<!-- 内容 -->
			<uni-section class="mb-10" title="3.发布内容" type="line" titleColor="#909399"></uni-section>
			<view class="content-input">
				<u--textarea v-model="content" placeholder="请输入发布内容"  :count="true"  maxlength=400 ></u--textarea>
			</view>
			<!--图片信息-->
			<uni-section class="mb-10" title="4.图片信息(选填)" type="line" titleColor="#909399"></uni-section>
			<view class="img-input">
				<image :src="item" v-if="item" mode="" class="imglist" v-for="(item,index) in imagesList" :key="item" @tap="ViewImage(index)" @longpress="deleteImg(index)"></image>
				<view class="box">
					<text class="t-icon t-icon-Rrl_s_114" style="width: 80rpx; height: 80rpx;margin-top: 36rpx;" @click="addImages()"></text>
				</view>
			</view>
			<!-- 备注信息 -->
			<uni-section class="mb-10" title="5.备注信息(选填)" type="line" titleColor="#909399"></uni-section>
			<view class="beizhu-input">
				<u--textarea v-model="bezhu" placeholder="请输入备注内容"  :count="true"  maxlength=100 ></u--textarea>
			</view>
			<!-- 地址 -->
			<uni-section class="mb-10" title="6.地址信息" type="line" titleColor="#909399"></uni-section>
			<view class="address-input">
				<u--input placeholder="请输入地址" v-model="address"  clearable></u--input>
			</view>
			<view class="addressbutton"> 
				<u-button
					text="选择地址"
					size="normal"
					type="primary"
					@click="addressclick"
				></u-button>
			</view>
			<!-- 金额 -->
			<uni-section class="mb-10" title="7.发布金额" type="line" titleColor="#909399"></uni-section>
			<view class="price-input">
				<u--input 
				placeholder="请输入价格"  
				@input="checknumber()"
				type = number
				v-model="price"  
				clearable></u--input> 
			</view>
			<text style="margin-left: 20rpx;color: #3c9cff;">元</text>
			<!-- 是否开启匿名 -->
			<text style="margin-left: 84rpx; font-size: 28rpx; color: #909399;">匿名</text>
			<view class="anonymous">  
				<u-switch v-model="huadong" activeColor=" #3c9cff" ></u-switch>
			</view>
			<!-- 发布按钮 -->
			<view class="fabubutton">
				<u-button
					text="创             建"
					size="normal"
					type="primary"
					@click="fbclick"
				></u-button>
			</view>
		</view> 
	</view> 
</template>  

<script> 
	import OSS from 'ali-oss' 
	import {uploadImgToOss,deleteImg} from "../../static/service/aliyoss/config.js"
	import {uploadImage} from '../../js_sdk/yushijie-ossutil/ossutil/uploadFile.js'
	import {http} from "../../static/service/requestAddress/rtas.js"
	export default {
		data() {
			return{ 
				show: false,
				issueType:"", //类型
				order_index:[],//订单类型下标数组，用于发布封装订单
				title:"", //标题
				content:"",//内容
				bezhu:"",//备注
				price:"",//价格
				order_img:"",//订单图片
				huadong:false,//匿名滑动选择器
				contacts:"",//联系人
				contacts_phone:"",//联系人电话
				address:"",//地址
				addressInfo:{ //地址信息对象
					id:"",
					name:"",
					phone:"",
					address:"",
					defaultaddress:false,
				},
                columns: [
                    ['帮我买', '帮我送',"帮我做"],
					["零食","药品","小吃","水果","饮料奶茶","主食套餐","生活用品","学习用品","其他"]
				],
                columnData: [
                ["零食","药品","小吃","水果","饮料奶茶","主食套餐","生活用品","学习用品","其他"],
				['文件', '钥匙', '花', '蛋糕',"物品","其他"],
				["打印资料","寄取快递","食堂打饭","排队服务","代写服务","其他服务"],
				["校园网类型","拼车类型"]
                ],
				imagesList:[],//图片数组
				receiveImgList: "",//上传图片返回的链接
			}
		},
		onLoad() {
				//清空数据
				this.issueType = "", //类型
				this.order_index=[],//订单类型下标数组，用于发布封装订单
				this.title="", //标题
				this.content="",//内容
				this.bezhu="",//备注
				this.price="",//价格
				this.order_img="",//订单图片
				this.huadong=false,//匿名滑动选择器
				this.contacts="",//联系人
				this.contacts_phone="",//联系人电话
				this.address="",//地址
				this.addressInfo ={ //地址信息对象
					id:"",
					name:"",
					phone:"",
					address:"",
					defaultaddress:false,
				},
				this.imagesList = []//图片数组
		},
		onShow() {
			//设置tabbar
			var str = uni.getStorageSync("tabbar")
			if(typeof str == 'string' && str.length != 0){
				var num = parseInt(str)
				if(num > 0){
					uni.setTabBarBadge({ //显示数字
						index: 1, //tabbar下标
						text:""+num,//数字
						success() {
						console.log("设置成功") 
						},
						fail(e){ 
						   console.log("设置失败"+JSON.stringify(e))
						}
					})
					uni.setStorageSync("tabbar",JSON.stringify(num))
					this.$forceUpdate()
				}
			}
			//监听地址页面传递的参数
			uni.$on("address",res=>{
				this.$nextTick(()=>{ //延伸步骤做伪刷新 
				    this.address = res.address
					this.contacts = res.name
					this.contacts_phone = res.phone
				})
			})
			
		},
		onUnload() {
				//清空数据
				this.issueType = "", //类型
				this.order_index=[],//订单类型下标数组，用于发布封装订单
				this.title="", //标题
				this.content="",//内容
				this.bezhu="",//备注
				this.price="",//价格
				this.order_img="",//订单图片
				this.huadong=false,//匿名滑动选择器
				this.contacts="",//联系人
				this.contacts_phone="",//联系人电话
				this.address="",//地址
				this.addressInfo ={ //地址信息对象
					id:"",
					name:"",
					phone:"",
					address:"",
					defaultaddress:false,
				},
				this.imagesList = []//图片数组
		},
		methods: {
			typechange(){ //点击选择发布类型输入框
				this.show = true
			},
			close(){//关闭选择框
				this.show=false
			},
			changeHandler(e) {
                const {
                    columnIndex, //
                    value,  //选择的结果
                    values, // values为当前变化列的数组内容
                    index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
                    picker = this.$refs.uPicker
                } = e
                // 当第一列值发生变化时，变化第二列(后一列)对应的选项
                if (columnIndex === 0) {
                    // picker为选择器this实例，变化第二列对应的选项
                    picker.setColumnValues(1, this.columnData[index])
                }
            },
			// 回调参数为包含columnIndex、value、values
			confirm(e) {
				console.log(JSON.stringify(e))
				this.order_index = e.indexs
				this.issueType = e.value[0]+"  /  "+e.value[1]
                this.show = false
			},
			// 上传图片
			addImages() {
				uni.$emit("uploadimg",false)
				var urlt 
				var that = this
				var promise = new Promise(function(resolve,reject){
				if(that.imagesList.length < 8){
					uni.chooseImage({
						count: 3, // 默认最多一次选择8张图
						sourceType: ['album', 'camera'], //图片来源
						success: res => {
							console.log("图片路径是："+ res.tempFilePaths);
							// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
							var tempFilePaths = res.tempFilePaths;
							//支持多图上传
							var falge = false//是否有不合法数据格式标记
							for (var i = 0; i < res.tempFilePaths.length; i++) {
								//对上传的图片校验
								var str = tempFilePaths[i].slice(tempFilePaths[i].length - 3,tempFilePaths[i].length)
								var strhz = ["jpg","png","gif"]
								var T = strhz.indexOf(str)
								if(T == -1){
									falge = true
									continue
								}
								if(that.imagesList.length < 3){
									//显示消息提示框
									uni.showLoading({
										mask: true
									})
									that.imagesList.push(tempFilePaths[i])
								}else{
									uni.$u.toast("图片只能上传3张！")
									break
								}
							}
							uni.hideLoading();
							if(falge){
								uni.$u.toast("上传成功，以过滤格式不正确图片！")
							}else{
								uni.$u.toast("图片上传成功！")
							}
							resolve()
						}
					})
				}else{
					uni.$u.toast("图片只能上传3张！")
				}
			})
			promise.then(res=>{
				setTimeout(function(){
					uni.$emit("uploadimg",true)
				},500)
			})
		
	 	},
			
			//预览图片
			ViewImage(index) {
				uni.previewImage({
					urls: this.imagesList,
					current: index
				});
			},
			//地址信息按钮跳转
			addressclick(){
				uni.navigateTo({
					// url:"/pages/massage/orderDetails",
					 url:'/address/address'
				})
			},
			//价格输入框检查只能为数字
			checknumber(){
				 let num = /^[1-9]([0-9])*$/
				 var b = num.test(this.price)
				 if(! b){
					setTimeout(() => { 
						this.price = ""  
						uni.$u.toast("价格只能是数字并且不能为0")
					},10)
				}
			},
			//图片长按删除
			deleteImg(index){
				var list = []
				for(var i = 0;i<this.imagesList.length;i++){
					if(index == i){
						continue
					}else{
						list.push(this.imagesList[i])
					}
				}
				this.imagesList = list
			},
			async fbclick(){
				//1.发布信息检查
				var user = uni.getStorageSync('user')
				if(! user){
					uni.$u.toast("您还未登录，登录才能发布订单")
					return
				}else if(this.issueType == "" || this.issueType.length == 0){
					uni.$u.toast("类型不能为空")
					return
				}else if (this.title == "" || this.issueType.length == 0 || this.title.length > 10){
					uni.$u.toast("标题不能为空，并且长度小于10")
					return
				}else if(this.content == "" || this.content.length == 0){
					uni.$u.toast("内容不能为空")
					return
				}else{
					//上传图片
					//显示消息提示框
					uni.showLoading({
						title:"正在创建中",
						mask: true
					})
					var path = this.issueType.replace(/\s*/g,"")
					console.log("进入上传图片")
					this.receiveImgList = await uploadImgToOss(this.imagesList,path)
					console.log("上传图片完成")
					//请求参数数组
					var sendpost = [
						http+"buyorder",
						http+"sendorder",
						http+"workorder",
						http+"need",
					]
					//封装请求对象
					var hidename = 0//匿名
					if(this.huadong == true){
						hidename = 1
					}
					var postData = {
						id:"",//订单id
						type:this.order_index[1] + 1,//订单类型
						title:this.title,//订单标题
						content:this.content,//订单内容
						orderImg:this.receiveImgList,//订单图片
						state:0,//订单状态
						remarks:this.bezhu,//订单备注
						price:this.price,//订单价格
						hideName:hidename,//是否匿名
						issueUser:(JSON.parse(user)).id,//发布用户
						issueUserName:(JSON.parse(user)).name,//发布用户名
						issueUserImg:(JSON.parse(user)).img,//发布用户头像
						contacts:this.contacts,//联系人姓名
						contactsPhone:this.contacts_phone,//联系人电话
						contactsAddress:this.address,//地址信息
						ordertypeid: this.order_index[0] + 1,//订单所属类型
					}	
					var URL = sendpost[this.order_index[0]]
					console.log('想后端发送请求'+URL)
					 uni.request({
						url:URL,
						method:"POST",
						data:postData,
						complete:(res) =>{
							if(res.data.code == 20011){
								uni.$u.toast("订单创建成功！")
								uni.redirectTo({
								url:"/pages/massage/orderDetails?data="+ JSON.stringify(res.data.date)
								})
								uni.hideLoading()
							}else{
								uni.$u.toast("订单创建失败！含有敏感词,请修改！")
							}
						}
					})
				}
			},
		}
	 } 
</script>

<style scoped>
	@import url("@/static/css/issue.css");
	page {
		background-color: #f5f5f5;
	}
</style>